package com.poem.springboot_rear.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.poem.springboot_rear.common.LogAs;
import com.poem.springboot_rear.common.LogType;
import com.poem.springboot_rear.common.Result;
import com.poem.springboot_rear.entity.News;
import com.poem.springboot_rear.entity.User;
import com.poem.springboot_rear.service.NewsService;
import com.poem.springboot_rear.service.UserService;
import com.poem.springboot_rear.utils.TokenUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功能：新闻的接口
 * 作者：小祝小祝
 * 日期： 2023/11/12 20:54
 */
@CrossOrigin
@RestController
@RequestMapping("/news")  // 一级路由
public class NewsController {

    @Resource
    NewsService newsService;
    @Resource
    UserService userService;

    /**
     * 新增信息
     */
    @LogAs(operation = "新增活动信息",type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody News news) {
        User currentUser = TokenUtils.getCurrentUser(); // 获取当前登录的用户信息
        news.setAuthorid(currentUser.getId()); // 获取登录信息里的用户id
        news.setTime(DateUtil.now()); // 获取当前时间 格式：2023-11-19 14:00:00
        // try catch 捕获异常
        try {
            newsService.save(news);
        } catch (Exception e) {
            // 判断异常的类型，然后返回不同的提示信息
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 修改信息
     */
    @LogAs(operation = "修改活动信息",type = LogType.UPDATE)
    @PostMapping("/update")
    public Result update(@RequestBody News news) {
        // try catch 捕获异常
        try {
            newsService.updateById(news);
        } catch (Exception e) {
            // 判断异常的类型，然后返回不同的提示信息
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 删除信息
     */
    
    @LogAs(operation = "删除活动信息",type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        newsService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除信息
     */
    @LogAs(operation = "批量删除活动信息",type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        newsService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 查询全部信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
//        List<News> newsList = newsService.list();
        // select * from news order by id desc  把查到的信息倒序
        List<News> newsList = newsService.list(new QueryWrapper<News>().orderByDesc("id"));
        return Result.success(newsList);
    }

    /**
     * 根据ID查询信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        News news = newsService.getById(id);
        User user = userService.getById(news.getId());
        if (user != null){
            news.setAuthor(user.getName());
        }
        return Result.success(news);
    }

    /**
     * 根据newsname name 分页模糊查询用户信息
     * PageIndex 当前页码
     * PageSize  每页多少行数据
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageIndex,
                               @RequestParam Integer pageSize,
                               @RequestParam String title) {
        // 条件构造器
        QueryWrapper<News> queryWrapper = new QueryWrapper<News>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        Page<News> page = newsService.page(new Page<>(pageIndex, pageSize), queryWrapper);
        // 把page的信息存储进records
        List<News> records = page.getRecords();
        // 通过for循环list，从中拿出每行数据的id，然后通过id去查询user表
        for (News record : records){
            Integer authorid = record.getAuthorid();
            // 把查到的数据存储
            User user = userService.getById(authorid);
            // 判断查到的数据是否为空，不为空的话就把其中的姓名写入我们返回给前端的数据当中
            if (user != null){
                record.setAuthor(user.getName());
            }
        }
        return Result.success(page);
    }
}
